const router = require('koa-router')()
let {appid, mch_id, key, appsecret, domain} = require('../config')
let parser = require('xml2json');
let request = require('request-promise')
let requestA = require('request')
let nanoid = require('nanoid')
let Order = require('../models/order')
let util = require('util');
let fs = require('fs');
let path = require('path');
let writeFile = util.promisify(fs.writeFile);
let {sign, formatMessage, paySign} = require('../libs/util')
router.prefix('/wx')

router.post('/' ,async (ctx, next) => {
  let {num, openid} = ctx.request.body
  num = parseFloat(num)
  if (typeof parseFloat(num) != "number") {
    throw new Error('金额必须是数据')
  }

  let obj = {
      appid: appid,
      body: 'aaaa',
      mch_id: mch_id,
      nonce_str: RndNum(32),
      notify_url: 'https://www.greatforworld.com/wx/notification', //通知地址
      openid,
      out_trade_no: `${Date.now()}${nanoid() }`.slice(0,30), // 商户订单号
      spbill_create_ip: ctx.ip.replace(/::ffff:/, ''), // 终端IP
      //spbill_create_ip: '192.168.1.2', // 终端IP
      total_fee: num * 100, // 标价金额
      trade_type: 'JSAPI', // 标价币种 默认人民币：CNY
      key
  }

  let signStr = sign(obj)


  let xml = `<xml>
     <appid>${obj.appid}</appid>
     <body>${obj.body}</body>
     <mch_id>${obj.mch_id}</mch_id>
     <nonce_str>${obj.nonce_str}</nonce_str>
     <notify_url>${obj.notify_url}</notify_url>
      <openid>${obj.openid}</openid>
     <out_trade_no>${obj.out_trade_no}</out_trade_no>
     <spbill_create_ip>${obj.spbill_create_ip}</spbill_create_ip>
     <total_fee>${obj.total_fee}</total_fee>
     <trade_type>${obj.trade_type}</trade_type>
     <sign>${signStr}</sign>
  </xml>`

    let options = {
      uri: `https://api.mch.weixin.qq.com/pay/unifiedorder`,
        method: 'POST',
        json: true,
        body: xml
    }
    let res = await request(options)
    let result = formatMessage(JSON.parse(parser.toJson(res)).xml);

    if (result.return_code === 'SUCCESS' && result.result_code === 'SUCCESS') {
        let timeStamp = parseInt(Date.now()/1000)
        let paySignStr = paySign({appid, nonceStr:obj.nonce_str, prepay_id: `prepay_id=${result.prepay_id}`, timeStamp, key})
        ctx.body = {code: 0, data: {prepay_id: result.prepay_id, paySignStr,timeStamp, nonceStr: obj.nonce_str}}
    }
})

router.all('/notification', async (ctx, next) => {
  console.log('11111111111111get:', ctx.query)
  console.log('22222222222222222:', ctx.request.body)

  console.log(`${ctx.method} ${ctx.url}`)
})

/**
 * 获取用户信息
 * @type {Object}
 */
router.post('/getUser', async (ctx, next) => {
  try {
    let {code} = ctx.request.body
    let options = {
      uri: `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${appsecret}&js_code=${code}&grant_type=authorization_code`,
      method: 'GET',
      json: true
    }

    let res = await request(options)
    ctx.body = {code: 0, data: res}
  }catch(err) {
    ctx.body = {code: -1, errmsg:`eror:${err}`}
  }
})


router.get('/createCode', async (ctx, next) => {
  try {
    let {scene, page, width=430} = ctx.query
    let options = {
      url: `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${ctx.token}`,
      method: 'POST',
      json: true,
      body: {
        scene,
        page,
        width
      }
    }
    let timer = Date.now()
    requestA({
     method: 'POST',
     url: `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${ctx.token}`,
     body: JSON.stringify({
       scene,
       page,
       width
     })
   }).pipe(fs.createWriteStream(`./public/images/code/${timer}.png`));
      ctx.body = {code: 0, data: `${domain}/images/code/${timer}.png`}
  }catch(err) {
    ctx.body = {code: -1, errmsg: `生成小程序二维码失败`}
  }
})




function RndNum(n){
    var rnd="";
    for(var i=0;i<n;i++)
        rnd+=Math.floor(Math.random()*10);
    return rnd;
}

module.exports = router
